package com.bwc.aidemo.paoqian

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.bwc.aidemo.R
import com.bwc.aidemo.amap.AmapAcyivity
import com.bwc.aidemo.arouter.RoutePath
import com.bwc.aidemo.base.BaseActivity
import com.bwc.aidemo.databinding.ActivityPaoqianBinding
import com.bwc.aidemo.http.ApiClients
import com.bwc.aidemo.util.MMKVUtil
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.regex.Pattern


class PaoqianActivity : BaseActivity<ActivityPaoqianBinding>() {
    private lateinit var weeklyDataList: List<List<DailyData>>

    override fun getLayoutId(): Int {
        return R.layout.activity_paoqian
    }

    override fun initViews() {

        val data = MMKVUtil.get("wenben","null")
        val regex = """\+{3}(.*?)\+{3}""".toRegex(RegexOption.DOT_MATCHES_ALL)

        val result = regex.find(data)?.groups?.get(1)?.value?.trimIndent()

        // 打印提取结果
        if (result != null) {
            Log.d("TAG", "initViews: ${result}")

            val parsedDetails = TrainingDataParser.parse(result)
            Log.d("TAG", "initViews: ${parsedDetails}")


            weeklyDataList = TrainingDataParser.generateWeeklyData(parsedDetails)

            // 3. 设置适配器
            dataBinding.vpWeekPager.adapter = WeekPagerAdapter(this, weeklyDataList) { dailyData ->
                showDetailDialog(dailyData)
            }

            // 4. 监听滑动更新标题
            dataBinding.vpWeekPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    val currentWeek = weeklyDataList[position].first().week
                    dataBinding.tvWeekTitle.text = "第${currentWeek}周"
                }
            })

            // 初始标题
            dataBinding.tvWeekTitle.text = "第1周"
        } else {
            println("没有找到符合条件的数据。")
        }


    }


    @SuppressLint("MissingInflatedId")
    private fun showDetailDialog(dailyData: DailyData) {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_training_detail, null)
        val training = dailyData.training

        // 1. 先创建对话框实例（不立即显示）
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(true)
            .create() // 创建对话框但不显示

        // 2. 关闭按钮点击事件：直接使用对话框实例关闭
        dialogView.findViewById<Button>(R.id.btn_close).setOnClickListener {
            dialog.dismiss() // 正确关闭方式
        }
//        跳转去跑步
        dialogView.findViewById<Button>(R.id.btn_go_start).setOnClickListener {
            getVoice(dailyData)
        }

        // 3. 处理训练/休息状态显示
        if (training == null) {
            // 休息状态
            dialogView.findViewById<TextView>(R.id.tv_title).text = "今日休息"
            dialogView.findViewById<LinearLayout>(R.id.ll_training_details).visibility = View.GONE
            dialogView.findViewById<TextView>(R.id.tv_rest_hint).visibility = View.VISIBLE
            dialogView.findViewById<Button>(R.id.btn_go_start).visibility = View.GONE
        } else {
            // 训练状态
            dialogView.findViewById<TextView>(R.id.tv_title).text = "训练详情"
            dialogView.findViewById<TextView>(R.id.tv_detail_date).text = "第${training.week}周 ${training.day}"
            dialogView.findViewById<TextView>(R.id.tv_detail_type).text = training.type
            dialogView.findViewById<TextView>(R.id.tv_detail_distance).text = training.distance
            dialogView.findViewById<TextView>(R.id.tv_detail_duration).text = training.duration
            dialogView.findViewById<TextView>(R.id.tv_detail_note).text = training.note
            dialogView.findViewById<Button>(R.id.btn_go_start).visibility = View.VISIBLE
        }

        // 4. 最后显示对话框
        dialog.show()
    }






    override fun initData() {

    }

    private val distanceList = mutableListOf<String>()
    private val durationList = mutableListOf<String>()

    private fun getVoice(dailyData: DailyData){

        Log.d("TAG", "getVoice: ${dailyData.training.toString()}")
        // 构建参数对象
        val params = SportWorkflowParameters(
            input = null,
            running = false,
            target = true,
            targetCalorie = null,
            targetDistance = dailyData.training?.distance,
            targetFrequency = null,
            targetHeart = null,
            targetSpeed = null,
            sportType = dailyData.training?.type,
            targetDuration = dailyData.training?.duration,
            note = dailyData.training?.note,
        )

        // 构建完整请求对象
        val request = SportWorkflowRequest(
            workflow_id = "7520151127414210600",
            parameters = params
        )

        ApiClients.apiService.sendVoices(request).enqueue(object : Callback<ResponseBody> {
            // Gson 实例（建议全局单例，这里简化直接创建）
            private val gson = Gson()

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful) {
                    val responseBodyStr = response.body()?.string() ?: return

                    // 第一步：解析外层 CozeApiResponse（不变）
                    val cozeApiResponse = gson.fromJson(responseBodyStr, CozeApiResponse::class.java)
                    if (cozeApiResponse.code != 0) return

                    // 第二步：解析内层 SportReminderData（此时 data 是带转义的字符串）
                    val sportReminderData = gson.fromJson(cozeApiResponse.data, SportReminderData::class.java)

                    // 关键：处理转义，将字符串转为 List<String>
                    val reminderList: List<String> = try {
                        // 去除字符串中的转义符（将 \" 转为 "）
                        val cleanedData = sportReminderData.data.replace("\\\"", "\"")
                        // 此时 cleanedData 格式为 ["当跑步0.5km时...", "当跑步1km时..."]
                        gson.fromJson(cleanedData, object : TypeToken<List<String>>() {}.type)
                    } catch (e: Exception) {
                        Log.e("paoqian", "数组转义处理失败", e)
                        emptyList() // 解析失败返回空列表
                    }


                    // 最终获取到的提醒列表
                    Log.d("paoqian", "解析成功，共 ${reminderList.size} 条提醒：")
                    reminderList.forEach { Log.d("paoqian", it) }
//                    val (distanceList, durationList) = parseLogToLists(reminderList)
//
//                    // 打印结果
//                    println("001距离列表：$distanceList")
//                    println("001时间列表：$durationList")

                    reminderList.forEach { item ->
                        when {
                            item.endsWith("km") -> distanceList.add(item)   // 距离（km结尾）
                            item.endsWith("min") -> durationList.add(item) // 时间（min结尾）
                        }
                    }

                    val distanceNumbers = distanceList.map { it.replace("km", "").toDouble() }
                    val durationNumbers = durationList.map { it.replace("min", "").toDouble() }

                    ARouter.getInstance().build(RoutePath.Amap)
                        .withBoolean("target",true)
                        .withSerializable("distanceNumbers",ArrayList(distanceNumbers))
                        .withSerializable("durationNumbers",ArrayList(durationNumbers))
                        .navigation()


                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                // 请求发送失败（如网络断开、连接超时、DNS解析失败）
                Log.e("paoqian", "请求发送失败", t)
                // TODO: 这里添加网络错误处理（如提示用户检查网络）
            }
        })

    }



    private fun parseLogToList(log: List<String>){

    }




}





// 1. 最外层 API 通用响应
data class CozeApiResponse(
    val code: Int,
    val msg: String,
    val detail: DetailBean,
    val usage: UsageBean,
    val data: String // 嵌套的 JSON 字符串，需二次解析
)

// 2. detail 子项（日志ID）
data class DetailBean(val logid: String)

// 3. usage 子项（Token 消耗）
data class UsageBean(
    val token_count: Int,
    val output_count: Int,
    val input_count: Int
)

// 4. data 二次解析后的业务数据（运动提醒列表）
data class SportReminderData(
    @SerializedName("content_type") val contentType: Int,
    @SerializedName("original_result") val originalResult: String?,
    @SerializedName("type_for_model") val typeForModel: Int,
    val data: String // 临时用 String 接收转义后的数组字符串
)


// 训练详情数据类
data class TrainingDetail(
    val week: Int, // 第几周
    val day: String, // 周几
    val type: String?, // 训练类型
    val distance: String?, // 距离
    val duration: String?, // 时长
    val note: String? // 备注
)

// 每日数据封装（包含训练数据或休息状态）
data class DailyData(
    val week: Int,
    val day: String,
    val training: TrainingDetail? // 为null则表示休息
)



